using System.Collections;
using System.Collections.Generic;
using Entitas;
using UnityEngine;

public class ClickSystem : ReactiveSystem<InputEntity>
{
    private Contexts _contexts;
    private ClickComponent _lastClickComponent;

    public ClickSystem(Contexts contexts) : base(contexts.input)
    {
        _contexts = contexts;
    }

    protected override ICollector<InputEntity> GetTrigger(IContext<InputEntity> context)
    {
        return context.CreateCollector(InputMatcher.Click);
    }

    protected override bool Filter(InputEntity entity)
    {
        return entity.hasClick;
    }

    protected override void Execute(List<InputEntity> entities)
    {
        InputEntity input = entities.SingleEntity();
        var click = input.click;
        var gameEntity = _contexts.game.GetEntitiesWithItemIndex(new CustomVector2(click.x, click.y));
        bool canMove = false;
        if (gameEntity != null)
        {
            canMove = gameEntity.SingleEntity().isMovable;
        }

        if (canMove)
        {
            if (_lastClickComponent == null)
            {
                _lastClickComponent = click;
            }
            else
            {
                if (click.x == _lastClickComponent.x - 1 && click.y == _lastClickComponent.y ||
                    click.x == _lastClickComponent.x + 1 && click.y == _lastClickComponent.y ||
                    click.x == _lastClickComponent.y - 1 && click.y == _lastClickComponent.x ||
                    click.x == _lastClickComponent.y + 1 && click.y == _lastClickComponent.x)
                {
                    ReplaceExchange(click);
                    ReplaceExchange(_lastClickComponent);
                    _lastClickComponent = null;
                }
            }
        }
    }

    private void ReplaceExchange(ClickComponent click)
    {
        var entities = _contexts.game.GetEntitiesWithItemIndex(new CustomVector2(click.x, click.y));
        foreach (GameEntity entity in entities)
        {
            entity.ReplaceExchange(ExchangeState.START);
        }
    }
}